<?php

namespace Joy\OAuth\Command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use Joy\OAuth\Helper\Str;

/**
 * 发布配置文件、迁移文件指令
 */
class PublishCommand extends Command
{
    use EnvHelperTrait;

    /**
     * 配置指令
     */
    protected function configure()
    {
        $this->setName('oauth:publish')->setDescription('发布 oauth 配置文件以及数据库迁移文件');
    }

    /**
     * 执行指令
     * @param Input  $input
     * @param Output $output
     * @return null|int
     * @throws LogicException
     * @see setCode()
     */
    protected function execute(Input $input, Output $output)
    {
        // 复制 migration 文件
        $destination = $this->app->getRootPath() . '/database/migrations/';
        if (! is_dir($destination)) {
            mkdir($destination, 0755, true);
        }
        
        $source = __DIR__.'/../../database/migrations/';
        $handle = dir($source);
        
        while ($entry=$handle->read()) {
            if (($entry != ".") && ($entry != "..")) {
                if (is_file($source.$entry)) {
                    copy($source.$entry, $destination.$entry);
                }
            }
        }
        $output->info('migration file copy successfully.');

        // 复制 oauth.php
        if (!file_exists(config_path().'oauth.php')) {
            copy(__DIR__.'/../../config/oauth.php', config_path().'oauth.php');
        }
        $output->info('oauth.php copy successfully.');

        // 在 .env 中设置 OAUTH_ENCRYPT_KEY
        if (!$this->envFileExists()) {
            if (! $this->exampleEnvFileExists()) {
                touch($this->envFile());
            } else {
                copy($this->exampleEnvFile(), $this->envFile());
            }
        }
        $key = Str::random(64);
        $updated = $this->updateEnvEntry('OAUTH_ENCRYPT_KEY', $key);
        
        if ($updated) {
            $output->info('oauth encrypt key set successfully: ' . $key);
        }
    }
}